package cn.devzyh.oms.coms.shipment.service;

import cn.devzyh.oms.common.core.message.ComsErrorCodes;
import cn.devzyh.oms.common.core.util.R;
import cn.devzyh.oms.coms.api.shipment.dto.ShipmentDTO;
import cn.devzyh.oms.coms.api.shipment.entity.ShipmentDetail;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 出库单单头
 *
 * @author devzyh
 * @date 2024-03-07
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShipmentService {

	private final ShipmentHeaderService headerService;

	private final ShipmentDetailService detailService;

	/**
	 * 保存出库单
	 *
	 * @param dto
	 * @return
	 */
	R save(ShipmentDTO dto) {
		R res = R.ok();
		boolean save = true;
		Long shipmentId = null;
		try {

			save = headerService.save(dto.getHeader());
			if (!save) {
				return R.failedMessage(ComsErrorCodes.SHIPMENT_SAVE_FAILED);
			}

			shipmentId = dto.getHeader().getId();
			for (ShipmentDetail detail : dto.getDetails()) {
				detail.setShipmentId(shipmentId);

				save = detailService.save(detail);
				if (!save) {
					return R.failedMessage(ComsErrorCodes.SHIPMENT_SAVE_FAILED, shipmentId.toString());
				}
			}
		} catch (Exception e) {
			res = R.failedMessage(e.getMessage());
		} finally {
			if (!save) {
				remove(shipmentId);
			}
		}
		return res;
	}

	/**
	 * 删除出库单
	 *
	 * @param shipmentId
	 * @return
	 */
	R remove(Long shipmentId) {
		if (shipmentId == null) {
			return R.failed();
		}

		headerService.removeById(shipmentId);
		detailService.remove(Wrappers.lambdaQuery(ShipmentDetail.class).eq(ShipmentDetail::getShipmentId, shipmentId));
		return R.ok();
	}

}